//
//  SendHttpOperation.m
//  OrderMeal
//
//  Created by 江苏宏创 on 14-7-21.
//  Copyright (c) 2014年 qkong. All rights reserved.
//

#import "SendHttpOperation.h"
#import <MKNetworkKit.h>
#import "UrlFile.h"
#import "defineFile.h"
void (^errorHandler)(MKNetworkOperation* completedOperation, NSError* error) = ^(MKNetworkOperation *completedOperation, NSError *error){
    [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewEnded" object:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": @"无网络连接,请重试"}];
};
@implementation SendHttpOperation

@synthesize passRegionDelegate,loginDelegate;

+(SendHttpOperation *)sharedHttpOperation{
    static dispatch_once_t once;
    static SendHttpOperation *httpOperation = nil;
    dispatch_once(&once, ^{
        httpOperation = [[SendHttpOperation alloc]init];
    });
    return httpOperation;
}

/**
 *  获取区域（分店）信息，以及该区的配送大厦。
 */
-(void)getRegions:(UITableViewController *)tableViewCtr{
        MKNetworkOperation *op = [hostEngine operationWithPath:regions_url];
        [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
            [tableViewCtr.refreshControl endRefreshing];
            [passRegionDelegate passRegions:completedOperation.responseJSON[@"retData"][@"regions"]];
        } errorHandler: ^(MKNetworkOperation *completedOperation, NSError *error){
            [tableViewCtr.refreshControl endRefreshing];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": @"无网络连接,请重试"}];
        }];
        [hostEngine enqueueOperation:op];
}

/**
 *  登录
 *
 *  @param username 用户名
 *  @param password 密码
 */
-(void)loginWithUsername:(NSString *)username Password:(NSString *)password{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewBegin" object:nil userInfo:@{@"waitMsg":@"登录中"}];
    
    NSDictionary *params = @{@"username": username,
                             @"password": password};
    MKNetworkOperation *op = [hostEngine operationWithPath:login_url params:params];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewEnded" object:nil];
        if ([successState  isEqualToNumber:@1]) {
        
            NSDictionary *userInfo = [[NSDictionary alloc]initWithDictionary:completedOperation.responseJSON[@"retData"]];
            [userDefaults setObject:username forKey:@"username"];
            [userDefaults setObject:password forKey:@"password"];
            [userDefaults setObject:userInfo[@"id"] forKey:@"customerId"];
            [userDefaults setObject:userInfo[@"lastName"] forKey:@"lastName"];
            [userDefaults setObject:userInfo[@"sex"] forKey:@"sex"];
            [userDefaults setObject:userInfo[@"email"] forKey:@"email"];
            [userDefaults setObject:userInfo[@"phone"] forKey:@"phone"];
            [userDefaults setObject:userInfo[@"building"][@"name"] forKey:@"building"];
            [userDefaults setObject:userInfo[@"address"] forKey:@"address"];
            [userDefaults setObject:userInfo[@"id"] forKey:@"customerId"];
            [userDefaults synchronize];
            [loginDelegate loginSuccess];
        }else{
          [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": completedOperation.responseJSON[@"msg"]}];
        }
    } errorHandler:errorHandler];
    
    [hostEngine enqueueOperation:op];
}

/**
 *  获取客户的详细积分信息,只能获取最近三个月的客户积分情况
 *
 *  @param customId 会员id
 */
-(void)getPointsWithcustomerId:(NSString *)customId UITableViewController:(UITableViewController *)tableViewCtr{
    
        MKNetworkOperation *op = [hostEngine operationWithPath:points_url params:@{@"customerId":customId}];
        
        [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
            [tableViewCtr.refreshControl endRefreshing];
            if ([successState isEqualToNumber:@1]) {
                [self.passPointsDelegate passPointsData:completedOperation.responseJSON[@"retData"]];
            }else{
                [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": @"无网络连接,请重试"}];
            }
        } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error){
            [tableViewCtr.refreshControl endRefreshing];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": @"无网络连接,请重试"}];
        }];
        [op onNotModified:^{
            
        }];
        [hostEngine enqueueOperation:op];

}

/**
 *  用户注册
 *
 *  @param email      邮箱
 *  @param lastName   姓名
 *  @param sex        性别
 *  @param phone      电话
 *  @param buildingid 大厦号
 *  @param address    地址
 *  @param password   密码
 */
-(void)registWithEmail:(NSString *)email
              lastName:(NSString *)lastName
                   sex:(NSString *)sex
                 phone:(NSString *)phone
            buildingid:(NSString *)buildingid
               address:(NSString *)address
              password:(NSString *)password{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewBegin" object:nil userInfo:@{@"waitMsg":@"注册中"}];
    
    NSDictionary *params = @{@"email":email,
                             @"lastName":lastName,
                             @"sex":sex,
                             @"phone":phone,
                             @"buildingid":buildingid,
                             @"address":address,
                             @"password":password};
    
    MKNetworkOperation *op = [hostEngine operationWithPath:register_url params:params];
    
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewEnded" object:nil];
        if ([completedOperation.responseJSON[@"msg"] isEqualToString:@"此邮箱已被注册，请您重新指定一个邮箱"]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": completedOperation.responseJSON[@"此邮箱已被注册"]}];
        }else{
           [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": completedOperation.responseJSON[@"msg"]}];
        }
    } errorHandler:errorHandler];
    
    [hostEngine enqueueOperation:op];
}

/**
 *  获取指定店面中某类型的商品列表
 *
 *  @param regionId    区/分店id
 *  @param date        日期格式为yyyy-MM-dd
 *  @param goodsTypeId 商品类型id
 */
-(void)getFoodListWithRegionId:(NSString *)regionId Date:(NSString *)date GoodsTypeId:(NSString *)goodsTypeId{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewBegin" object:nil userInfo:@{@"waitMsg":@"等待加载数据"}];
    
    NSDictionary *params = @{@"regionId":regionId,
                             @"date":date,
                             @"goodsTypeId":goodsTypeId};
    
    MKNetworkOperation *op = [hostEngine operationWithPath:regiongoods_url params:params];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"waitViewEnded" object:nil];
        if ([successState isEqualToNumber:@1]) {
            [self.passFoodDelegate passFoodData:completedOperation.responseJSON[@"retData"]];
            }else{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"errorMsg" object:nil userInfo:@{@"ERROR": completedOperation.responseJSON[@"加载数据失败"]}];
        }
    } errorHandler:errorHandler];
    [hostEngine enqueueOperation:op];
}
@end
